/*
 * Copyright(C) 2012 Luvina Software Company
 *
 * LoginNameValidator.java, Jun 7, 2012 HaiPD
 */
package net.luvina.manageuser.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import net.luvina.manageuser.util.Message;
import net.luvina.manageuser.util.StringUtill;

/**
 * Validate Login Name
 *
 * @author HaiPD
 *
 */
public class LoginNameValidator implements Validator {

	private static final String LOGIN_NAME_PATTERN = "^[A-Za-z_]{1}[A-Za-z0-9_]+$";
	private static final int MIN_LENGTH = 4;
	private static final int MAX_LENGTH = 15;
	private Pattern pattern;
	private Matcher matcher;

	/**
	 * Contrutor default
	 */
	public LoginNameValidator() {
		pattern = Pattern.compile(LOGIN_NAME_PATTERN);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object object) throws ValidatorException {
		String value = object.toString();
		String labelField = (String) component.getAttributes().get("label");
		if (StringUtill.checkMinMaxLeng(value, MIN_LENGTH, MAX_LENGTH)) {
			FacesMessage msg_er007 = new FacesMessage("「" + labelField + "」 を"
					+ MIN_LENGTH + "＜＝桁数、＜＝ " + MAX_LENGTH
					+ Message.getString("ER007"));
			msg_er007.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg_er007);
		}

		matcher = pattern.matcher(value);
		if (!matcher.matches()) {
			FacesMessage msg_er019 = new FacesMessage("「" + labelField + "」"
					+ Message.getString("ER019"));
			msg_er019.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg_er019);
		}
	}

}
